<script setup lang="ts">
import {
  getPaperAnswerListAPI,
  getPaperAPI,
  getStuListInfoAPI
} from '@/api/paper'
import type {
  AnswerListDataType,
  PaperInfoDataType,
  PaperStuListType,
  QueryDataType
} from '@/interface'
import { formatDate } from '@/utils/format'
import { Search } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import * as echarts from 'echarts'
import { chinaMap } from '@/assets/chinaMap'
import { socket } from '@/utils/socket'
import { ElMessage, ElMessageBox } from 'element-plus'
import { rejectAnswerAPI } from '@/api/answer'

const route = useRoute()

const mapContainer = ref()
const initMap = () => {
  const chinaCharts = echarts.init(mapContainer.value)
  echarts.registerMap('chinaMap', chinaMap as any)
  let option = {
    geo: {
      // 地理坐标组件
      type: 'map',
      map: 'chinaMap',
      zoom: 1.25,
      roam: true
    }
  }
  chinaCharts.setOption(option)
}
onMounted(() => {
  initMap()
})

// 获取试卷信息
const paperInfo = ref<PaperInfoDataType | null>(null)
const getPaperInfo = async () => {
  const { data: res } = await getPaperAPI(+route.params.id)
  if (res.status === 200) {
    paperInfo.value = res.data
  }
}
getPaperInfo()

// 获取考生列表信息
const userListTotal = ref(0)
const userListQuery = ref<QueryDataType>({
  id: +route.params.id,
  keyword: '',
  pageSize: 9,
  pageIndex: 1
})
const userList = ref<PaperStuListType[]>([])
const getStuListInfo = async () => {
  const { data: res } = await getStuListInfoAPI(userListQuery.value)
  if (res.status === 200) {
    userList.value = [...res.data]
    userListTotal.value = res.total
  }
}
getStuListInfo()

// 考生列表查询
const searchStuList = () => {
  userListQuery.value.pageIndex = 1
  getStuListInfo()
}

// 获取答卷列表
const answerListTotal = ref(0)
const answerListQuery = ref<QueryDataType>({
  id: +route.params.id,
  keyword: '',
  pageSize: 10,
  pageIndex: 1
})
const answerList = ref<AnswerListDataType[]>([])
const getPaperAnswerList = async () => {
  const { data: res } = await getPaperAnswerListAPI(answerListQuery.value)
  if (res.status === 200) {
    answerList.value = [...res.data]
    answerListTotal.value = res.total
  }
}
getPaperAnswerList()

// 答卷列表查询
const searchAnswerList = () => {
  answerListQuery.value.pageIndex = 1
  getPaperAnswerList()
}

// 考生列表换页
const handleStuListChangePage = (currentPage: number) => {
  userListQuery.value.pageIndex = currentPage
  getStuListInfo()
}

// 答卷列表换页
const handleAnsweListChangePage = (currentPage: number) => {
  answerListQuery.value.pageIndex = currentPage
  getPaperAnswerList()
}

// 前往批改试卷
const gotoJudge = (id: number) => {
  window.open(`/answer/judge?id=${id}`)
  // router.push({
  //   path: '',
  //   query: { id: id }
  // })
}

// 打回答卷
const rejectAnswer = (id: number) => {
  ElMessageBox.confirm('是否打回答卷', '打回操作', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const { data: res } = await rejectAnswerAPI(id)
      if (res.status === 200) {
        ElMessage.success(res.message)
        getPaperAnswerList()
        getStuListInfo()
      } else {
        ElMessage.error(res.message)
      }
    })
    .catch(() => {})
}

onMounted(() => {
  socket.emit('paperMonitor', {
    paper_id: route.params.id,
    user_id: JSON.parse(localStorage.getItem('user') as string).userData.id,
    admin: 1
  })

  socket.on('faceInfo', (data) => {
    userList.value.forEach((item) => {
      if (item.id === data.user_id) {
        item['faceImage2'] = data.face_info
        item['linkStatus'] = data.link_status
      }
    })
  })
  socket.on('monitorRefresh', (data) => {
    if (data) {
      getStuListInfo()
      getPaperAnswerList()
    }
  })
})
</script>

<template>
  <div class="monitor-container dark">
    <div class="monitor-left">
      <div class="monitor-left-top">
        <el-card class="monitor-paper-info" shadow="never">
          <template #header>试卷信息</template>
          <ul>
            <li>
              试卷名：
              <span>{{ paperInfo?.paperTitle }}</span>
            </li>
            <li>
              题目数：
              <span>{{ paperInfo?.question_count }}</span>
            </li>
            <li>
              试卷总分：
              <span>{{ paperInfo?.score }}</span>
            </li>
            <li>
              考试时长：
              <span>{{ paperInfo?.suggestTime }}</span>
            </li>
            <li>
              试卷创建人：
              <span>{{ paperInfo?.create_user }}</span>
            </li>
            <li>
              试卷创建时间：
              <span>{{
                formatDate(paperInfo?.create_time as Date, 'YYYY-MM-DD')
              }}</span>
            </li>
          </ul>
        </el-card>
        <div class="monitor-paper-map-box">
          <div class="monitor-paper-map" ref="mapContainer"></div>
          <el-card class="monitor-paper-map-list">
            <template #header> 位置信息 </template>
          </el-card>
        </div>
      </div>
      <el-card class="monitor-stu-list">
        <template #header>
          <div class="monitor-list-header">
            <span>考生列表</span>
            <div class="header-search">
              <el-input
                v-model="userListQuery.keyword"
                placeholder="请输入考生名"
                clearable
                :prefix-icon="Search"
                @clear="getStuListInfo"
              />
              <el-button type="primary" @click="searchStuList">搜索</el-button>
            </div>
          </div>
        </template>
        <div v-if="userList.length" class="monitor-stu-list-body">
          <el-scrollbar>
            <div class="stu-list">
              <el-tooltip
                placement="top"
                v-for="item in userList"
                :key="item.id"
              >
                <template #content>
                  <ul class="tooltipList">
                    <li>
                      <span>用户名:</span>
                      <span>{{ item.user_name }}</span>
                    </li>
                    <li>
                      <span>电话:</span>
                      <span>{{ item.phone }}</span>
                    </li>
                    <li>
                      <span>学院:</span>
                      <span>{{ item.collegeName }}</span>
                    </li>
                    <li>
                      <span>专业:</span>
                      <span>{{ item.departmentName }}</span>
                    </li>
                    <li>
                      <span>班级:</span>
                      <span>{{ item.className }}</span>
                    </li>
                    <li>
                      <span>性别:</span>
                      <span>{{ item.gender ? '女' : '男' }}</span>
                    </li>
                    <li>
                      <span>年龄:</span>
                      <span>{{ item.age }}</span>
                    </li>
                    <li>
                      <span>注册时间:</span>
                      <span>{{
                        formatDate(item.create_time as string, 'YYYY-MM-DD')
                      }}</span>
                    </li>
                  </ul>
                </template>
                <el-card>
                  <div class="stu-list-body">
                    <div class="stu-list-face-box">
                      <div class="stu-list-face">
                        <p>用户人脸</p>
                        <el-image
                          class="stu-list-face-img"
                          v-if="item.face_image"
                          :src="item.face_image"
                          :previewSrcList="[item.face_image]"
                          hide-on-click-modal
                        />
                        <img
                          class="stu-list-face-img"
                          v-else
                          src="../../assets/defaultAvatar.png"
                        />
                      </div>
                      <div class="stu-list-face2">
                        <p>实时人脸</p>
                        <el-image
                          class="stu-list-face-img"
                          v-if="item.faceImage2"
                          :src="item.faceImage2"
                          :previewSrcList="[item.faceImage2]"
                        />
                        <img
                          class="stu-list-face-img"
                          v-else
                          src="../../assets/defaultAvatar.png"
                        />
                      </div>
                    </div>
                    <div class="stu-list-info">
                      <div class="stu-list-user-id">
                        <span>用户ID: </span>
                        <span>{{ item.id }}</span>
                      </div>
                      <div class="stu-list-user-name">
                        <span>真实姓名: </span>
                        <span>{{ item.real_name }}</span>
                      </div>
                      <div class="stu-list-status">
                        <span>状态: </span>
                        <el-tag :type="item.linkStatus ? 'success' : 'warning'">
                          {{ item.linkStatus ? '已连接' : '未连接' }}
                        </el-tag>
                      </div>
                      <div class="stu-list-address">
                        <span>IP地址: </span>
                        <el-tag type="primary">{{
                          item.ipaddress || '暂无'
                        }}</el-tag>
                      </div>
                    </div>
                  </div>
                </el-card>
              </el-tooltip>
            </div>
          </el-scrollbar>
          <el-pagination
            background
            layout="prev, pager, next"
            :page-size="9"
            :total="userListTotal"
            style="margin-top: 0.875rem"
            @change="handleStuListChangePage"
          />
        </div>
        <el-empty v-else style="width: 100%"></el-empty>
      </el-card>
    </div>
    <div class="monitor-right">
      <el-card class="monitor-answer-list">
        <template #header>
          <div class="monitor-list-header">
            <span>提交答卷列表</span>
            <div class="header-search">
              <el-input
                v-model="answerListQuery.keyword"
                placeholder="请输入考生名"
                clearable
                :prefix-icon="Search"
                @clear="getPaperAnswerList"
              />
              <el-button type="primary" @click="searchAnswerList"
                >搜索</el-button
              >
            </div>
          </div>
        </template>
        <div v-if="answerList.length" class="monitor-answer-list-body">
          <el-scrollbar>
            <div class="answer-list">
              <el-card v-for="item in answerList" :key="item.answer_user_id">
                <div class="answer-list-item">
                  <span>试卷ID</span>
                  <div class="answer-list-item-content">
                    <span>{{ item.id }}</span>
                  </div>
                </div>
                <div class="answer-list-item">
                  <span>考生名</span>
                  <div class="answer-list-item-content">
                    <span>{{ item.answer_user }}</span>
                  </div>
                </div>
                <div class="answer-list-item">
                  <span>提交时人脸</span>
                  <div class="answer-list-item-content">
                    <el-image
                      :src="item.answer_user_face"
                      style="width: 100px; height: 100px"
                      :previewSrcList="[item.answer_user_face]"
                    />
                  </div>
                </div>
                <div class="answer-list-item">
                  <span>状态</span>
                  <div class="answer-list-item-content">
                    <el-tag :type="item.status ? 'success' : 'warning'">
                      {{ item.status ? '已批改' : '未批改' }}
                    </el-tag>
                  </div>
                </div>
                <div class="answer-list-item">
                  <span>操作</span>
                  <div class="answer-list-item-content">
                    <el-button
                      :type="!item.status ? 'warning' : 'primary'"
                      size="small"
                      plain
                      @click="gotoJudge(item.id)"
                    >
                      {{ !item.status ? '批改' : '查看' }}
                    </el-button>
                    <el-button
                      type="danger"
                      plain
                      size="small"
                      @click="rejectAnswer(item.id)"
                      >打回</el-button
                    >
                  </div>
                </div>
              </el-card>
            </div>
          </el-scrollbar>
          <el-pagination
            background
            layout="prev, pager, next"
            :page-size="10"
            :total="answerListTotal"
            style="margin-top: 14px"
            @change="handleAnsweListChangePage"
          />
        </div>
        <el-empty v-else style="width: 100%" description="暂无提交"></el-empty>
      </el-card>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.monitor-container {
  width: 100vw;
  height: 100vh;
  padding: 0.625rem;
  display: flex;
  .el-card {
    :deep(.el-card__header) {
      padding: 0.875rem 1rem;
    }
    :deep(.el-card__body) {
      width: 100%;
      flex: 1;
      display: flex;
      padding: 14px;
    }
  }
  .monitor-left {
    flex: 7;
    display: flex;
    flex-direction: column;
    margin-right: 1.25rem;
    .monitor-left-top {
      flex: 1;
      margin-bottom: 1.25rem;
      display: flex;
      justify-content: space-between;
      .monitor-paper-info {
        width: 22.625rem;
      }
      .monitor-paper-map-box {
        width: 100%;
        display: flex;
        align-items: center;
        .monitor-paper-map {
          width: 50%;
          height: 100%;
        }
        .monitor-paper-map-list {
          width: 50%;
          height: 100%;
        }
      }
    }
    .monitor-stu-list {
      display: flex;
      flex-direction: column;
      flex: 1.1;

      .monitor-stu-list-body {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: calc((11.25rem + 0.875rem) * 2);
        .stu-list {
          display: flex;
          flex-wrap: wrap;
          justify-content: flex-start;
          width: 100%;
          height: 100%;
          margin-bottom: 0.625rem;

          :global(.tooltipList span:nth-child(1)) {
            display: inline-block;
            min-width: 50px;
            text-align: right;
            margin-right: 0.75rem;
          }
          .el-card {
            width: 33%;
            margin-bottom: 0.875rem;
            margin-right: 0.5%;
            &:nth-child(3n) {
              margin-right: 0;
            }
          }
          .stu-list-body {
            display: flex;
            width: 100%;
            justify-content: flex-start;
            font-size: 0.875rem;
            .stu-list-face-box {
              display: flex;
              margin-right: 1rem;
              .stu-list-face {
                margin-right: 0.75rem;
              }
              .stu-list-face,
              .stu-list-face2 {
                display: flex;
                flex-direction: column;
                align-items: center;
                p {
                  margin-bottom: 0.5rem;
                }
                .stu-list-face-img {
                  width: 6.25rem;
                  height: 6.25rem;
                  border-radius: 0.375rem;
                  overflow: hidden;
                }
              }
            }
            .stu-list-info {
              height: 100%;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
            }
          }
        }
      }
    }
  }
  .monitor-right {
    flex: 3;
    display: flex;
    .monitor-answer-list {
      display: flex;
      flex-direction: column;
      flex: 1;

      .monitor-answer-list-body {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: calc((9.8125rem + 0.875rem) * 5 - 0.875rem);
        .answer-list {
          width: 100%;
          height: 100%;
          font-size: 0.875rem;
          .el-card {
            margin-bottom: 0.875rem;
          }
          .answer-list-item {
            display: flex;
            flex: 1;
            flex-direction: column;
            align-items: center;
            padding: 0 8px;
            & > span {
              margin-bottom: 0.625rem;
            }
            .answer-list-item-content {
              width: 100%;
              height: 100%;
              display: flex;
              justify-content: center;
              align-items: center;
            }
          }
        }
      }
    }
  }
  .monitor-list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .header-search {
      display: flex;
      & > :first-child {
        margin-right: 10px;
      }
    }
  }
}
</style>
